package ink.ykb.snowflake.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局处理异常
 */
@Slf4j
@ControllerAdvice
public class GlobalErrorController {

    @Autowired
    private MessageUtil messageUtil;
    
	@ExceptionHandler(value = {BindException.class,MethodArgumentNotValidException.class})
	@ResponseBody
    public  ResponseMsg<String> bindExceptionHandler(Exception e) {
		
		String code = null;
		String field = null;
		if(e instanceof BindException){
			BindException e1 =  (BindException)e;
	    	code = e1.getBindingResult().getFieldError().getDefaultMessage();
	    	field = e1.getBindingResult().getFieldError().getField();
		}else if(e instanceof MethodArgumentNotValidException){
			MethodArgumentNotValidException e1 = (MethodArgumentNotValidException)e;
			field = e1.getBindingResult().getFieldError().getField();
	    	code = e1.getBindingResult().getFieldError().getDefaultMessage();
		}
		
		log.error("参数校验失败：{}" ,field);
		if(StringUtils.isBlank(code)){
    		code = CodeConstant.FAIL_000001;
    	}
    	return new ResponseMsg<>(code,messageUtil.getMessage(code));
    	
    }

	@ExceptionHandler(ServiceException.class)
	@ResponseBody
    public ResponseMsg<Object> serviceException(ServiceException e) {
        log.error("异常信息： \n编号：{}\n消息：{}\n数据：{}\n位置：{}",
        		e.getCode(),
        		e.getMessage(),
        		e.getData()!= null?JSONObject.toJSONString(e.getData()):"",
        		(e.getStackTrace()!=null && e.getStackTrace().length > 0)?e.getStackTrace()[0].toString():e.getStackTrace());
        
        return new ResponseMsg<>(e.getCode(),e.getMessage(),e.getData());
    }

	@ExceptionHandler(Exception.class)
	@ResponseBody
    public ResponseMsg<String> exception(Exception e) {
        log.error("未知错误",e);
        return new ResponseMsg<>(CodeConstant.ERROR_999999,messageUtil.getMessage(CodeConstant.ERROR_999999),e.getMessage());
    }
}
